import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { isAuth } from '../../utils/auth';

// const AuthRoute = ({ component: Component, ...rest }) => {
//   // console.log(props);
//   return (
//     <Route
//       {...rest}
//       render={props =>
//         isAuth() ? (
//           <Component {...props} />
//         ) : (
//           <Redirect
//             to={{
//               pathname: '/login',
//               state: { from: props.location }
//             }}
//           />
//         )
//       }
//     />
//   );
// };
// eg:  <AuthRoute path="/map" component={Map}></AuthRoute>
const AuthRoute = ({ component: Component, ...rest }) => {
  return <Route {...rest} render={props => {
    const isLogin = isAuth()

    if (isLogin) {
      // 若已登录
      // 传递路由信息给Component
      return <Component {...props}></Component>
    } else {
      // 未登录
      // 重定向,state是本来需要跳转的目标页面，方便重定向后跳回来
      return <Redirect to={{
        pathname: '/login',
        state: {
          from: props.location
        }
      }}></Redirect>
    }
  }}></Route>
}

export default AuthRoute;
